using MauiBuilder.ViewModels;

namespace MauiBuilder.Views;

public partial class SpeechToTextPage : ContentPage
{
    public SpeechToTextPage(SpeechToTextViewModel viewModel)
    {
        InitializeComponent();
        BindingContext = viewModel;
    }

    protected override async void OnAppearing()
    {
        base.OnAppearing();
#if ANDROID
        bool IsSpeechRecognitionAvailable1 = OperatingSystem.IsAndroidVersionAtLeast(34);


        bool IsSpeechRecognitionAvailable2 = Android.Speech.SpeechRecognizer.IsOnDeviceRecognitionAvailable(Android.App.Application.Context);
#endif
        // 检查麦克风权限
        await CheckMicrophonePermission();
    }

    private async Task CheckMicrophonePermission()
    {
        try
        {
            var status = await Permissions.CheckStatusAsync<Permissions.Microphone>();
            
            if (status != PermissionStatus.Granted)
            {
                var shouldRequest = await DisplayAlert(
                    "需要权限", 
                    "语音识别功能需要麦克风权限，是否现在授予？", 
                    "授予", 
                    "取消");
                
                if (shouldRequest)
                {
                    var viewModel = BindingContext as SpeechToTextViewModel;
                    if (viewModel?.RequestPermissionsCommand.CanExecute(null) == true)
                    {
                        viewModel.RequestPermissionsCommand.Execute(null);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            await DisplayAlert("错误", $"检查权限时出错: {ex.Message}", "确定");
        }
    }
}